<?php
/**
* 系统用户模型
* lsj 2010-11-20
*/

if(!defined('APP_HOME')) exit('Access Denied');

class userMod extends lib_model
{
    protected $tbl = 'sys_users';#当前模型操作的主表
    protected $joinTableGroups = 'sys_groups';#要连接的用户组表名
	protected $key = array('group_id'=>'sys_groups.id');#当前模型要连接的表与对应外键
    protected $ckName = array();#COOKIE中的各键值名

	/*
	#初始化
	*/
	public function _init()
	{
        $this->ckName = loadConfig('user');
	}

 
    /*
    #检查用户名是否存在
    */
    public function isName($m)
    {
        $res = $this->setName($m)->select('id');
        if(null === $res) return 1;#不存在
        elseif($res) return count($res);#存在
        return false;#异常
    }
    
    /*
    #检查邮箱地址是否存在
    */
    public function isEmail($m)
    {
        $res = $this->setEmail($m)->select('id');
        if(null === $res) return 1;#不存在
        elseif($res) return count($res);#存在
        return false;#异常
    }

    /*
    #检查用户是否登录
    */
    public function isLogin()
    {
        if($_COOKIE[$this->ckName['ck_uid']] == '') return false;#用户ID
        if($_COOKIE[$this->ckName['ck_gid']] == '') return false;#用户组ID
        if($_COOKIE[$this->ckName['ck_name']] == '') return false;#用户名
        if($_COOKIE[$this->ckName['ck_gname']] == '') return false;#用户角色名
		if($_COOKIE[$this->ckName['ck_ltime']] == '') return false;#用户上次登录时间
		if($_COOKIE[$this->ckName['ck_ntime']] == '') return false;#用户本次登录时间
        if($_COOKIE[$this->ckName['ck_lip']] == '') return false;#用户上次登录IP
		if($_COOKIE[$this->ckName['ck_sig']] == '') return false;#用户本次登录签名

		#所有的COOKIE项与密钥串起来MD5出一个签名
		$sig = $this->ckName['ck_key'];
		$sig .= $_COOKIE[$this->ckName['ck_name']];
		$sig .= $_COOKIE[$this->ckName['ck_gname']];
		$sig .= $this->ckName['ck_key'];
		$sig .= $_COOKIE[$this->ckName['ck_ltime']];
		$sig .= $_COOKIE[$this->ckName['ck_ntime']];
		$sig .= $this->ckName['ck_key'];
		$sig .= $_COOKIE[$this->ckName['ck_uid']];
		$sig .= $_COOKIE[$this->ckName['ck_gid']];
		$sig .= $_COOKIE[$this->ckName['ck_lip']];
		$sig = md5(md5($sig).$this->ckName['ck_key']);

		if($sig == $_COOKIE[$this->ckName['ck_sig']]) return true;
		return false;#异常
	}

    /*
    #登录
    */
    public function login($name, $passwd)
    {
        if($name == '' || $passwd == '') return 0;#缺少参数
        
        //$this->setDebug();
        $sel[$this->tbl] = 'id,name,truename,group_id,lasttime,lastip,logins';
        $sel[$this->joinTableGroups] = 'name as gname';

		$user = $this->setLimit(1)
		->setName($name)
		->setPasswd($this->createPasswd($passwd))
		->joinTable($this->joinTableGroups)
		->select($sel);

		if(!$user){
            $is = $this->setLimit(1)
			->setName($name)
			->select('id');
			if(!$is) return -1;#用户名不存在
            return -2;#用户名与密码不一致
		}else{
			$ntm = $_SERVER['REQUEST_TIME'];
			$update = array();
			$update['lasttime'] = $ntm;
			$update['lastip'] = getIp();
			$update['logins'] = $user['logins'] + 1;

			if(!$this->update($update)) return -3;#用户登录信息更新失败

			#计算出登录签名
            $sig = $this->ckName['ck_key'];
			$sig .= $user['truename'];
			$sig .= $user['gname'];
			$sig .= $this->ckName['ck_key'];
			$sig .= date('Y-m-d H:i:s', $user['lasttime']);
			$sig .= date('Y-m-d H:i:s', $ntm);
			$sig .= $this->ckName['ck_key'];
			$sig .= $user['id'];
			$sig .= $user['group_id'];
			$sig .= $user['lastip'];
			$sig = md5(md5($sig).$this->ckName['ck_key']);

            #注册COOKIE
            if(!cookie($this->ckName['ck_uid'], $user['id'])) return -4;
            if(!cookie($this->ckName['ck_gid'], $user['group_id'])) return -5;
			if(!cookie($this->ckName['ck_name'], $user['truename'])) return -6;
			if(!cookie($this->ckName['ck_gname'], $user['gname'])) return -7;
			if(!cookie($this->ckName['ck_ltime'], date('Y-m-d H:i:s', $user['lasttime']))) return -8;
			if(!cookie($this->ckName['ck_ntime'], date('Y-m-d H:i:s', $ntm))) return -9;
			if(!cookie($this->ckName['ck_lip'], $user['lastip'])) return -10;
	        if(!cookie($this->ckName['ck_sig'], $sig)) return -11;

			return true;
		}
		return false;#异常
    }

    /*
    #退出
    */
    public function logout()
    {
		#把所有的COOKIE给清除掉
		$tm = 0 - 86400;
		if(!cookie($this->ckName['ck_uid'], '', $tm)) return false;
		if(!cookie($this->ckName['ck_gid'], '', $tm)) return false;
		if(!cookie($this->ckName['ck_name'], '', $tm)) return false;
		if(!cookie($this->ckName['ck_gname'], '', $tm)) return false;
		if(!cookie($this->ckName['ck_ltime'], '', $tm)) return false;
		if(!cookie($this->ckName['ck_ntime'], '', $tm)) return false;
		if(!cookie($this->ckName['ck_lip'], '', $tm)) return false;
        if(!cookie($this->ckName['ck_sig'], '', $tm)) return false;
		return true;
    }

   	/*
    #获取当前用户的ID
    */
	public function getNowUid()
	{
		return abs(intval($_COOKIE[$this->ckName['ck_uid']]));
	}
     
    /*
    #获取当前用户的组ID
    */
    public function getNowGid()
    {
       return abs(intval($_COOKIE[$this->ckName['ck_gid']]));
    }

    /*
    #获取当前已登录的用户名
    */
    public function getNowUname()
    {
       return trim($_COOKIE[$this->ckName['ck_name']]);
    }

    /*
    #获取当前已登录用户的组名
    */
    public function getNowGname()
    {
       return trim($_COOKIE[$this->ckName['ck_gname']]);
    }

    /*
    #获取当前已登录用户COOKIE信息
    */
    public function getNowInfo()
    {
       $info = array();
       $info['uid'] = abs(intval($_COOKIE[$this->ckName['ck_uid']]));
       $info['gid'] = abs(intval($_COOKIE[$this->ckName['ck_gid']]));
       $info['uname'] = trim($_COOKIE[$this->ckName['ck_name']]);
       $info['gname'] = trim($_COOKIE[$this->ckName['ck_gname']]);
       $info['ltime'] = trim($_COOKIE[$this->ckName['ck_ltime']]);
       $info['ntime'] = trim($_COOKIE[$this->ckName['ck_ntime']]);
       $info['lip'] = trim($_COOKIE[$this->ckName['ck_lip']]);
       
       return $info;
    }

    /*
    #获取各用户组下用户总数 
    */
    public function getGroupCount()
    {
    	$gcount = array();
    	$res = $this->groupBy('group_id')
    		 ->select('count(*) as c, group_id as gid');
    	if($res){
    		foreach($res as $key=>$val){
    			$gcount[$val['gid']] = $val['c'];
			}
		}
		return $gcount;
	}
    
    /*
    #获取指定ID的用户信息
    */
    public function getInfo($id = 0, $sel = '*')
    {
        if(!$id) $id = $this->getNowUid();
        if(!$id) return null;
        if(is_array($id)) $id = join(',', $id);
        else $this->setLimit(1);

        $res = $this->setId($id)->select($sel);
        return $res;
    }

    /*
    #获取用户列表
    #$num: 条数
    #$id: 指定用户ID
    #$sel: 查询的用户表字段
    */
	public function getUser($num=0, $id=0, $sel='*')
	{
		$sels = array();
        $sels[$this->tbl] = $sel;
        $sels[$this->joinTableGroups] = 'name as gname';

        if($num) $this->setLimit($num);
        if($id) $this->setId ($id);

        return $this->joinTable($this->joinTableGroups)->select($sels);
	}
    
    /*
    #添加用户
    */
    public function addUser($user)
    {
		return $this->insert($user);
    }

    /*
    #修改用户信息
    */
    public function editUser($user, $id = 0)
    {
		if($id) $this->setId($id);
		elseif(!empty($user['id'])) $this->setId($user['id']);
		if(isset($user['id'])) unset($user['id']);

		return $this->update($user);
    }

    /*
    #修改用户信息
    */
    public function delUser($id)
    {
		return $this->setId($id)->delete();
    }

    /*
    #修改用户密码
    */
    public function editPasswd($old, $new, $id)
    {
		$old = $this->createPasswd($old);
		$new = $this->createPasswd($new);
		$is = $this->setId($id)
			->setPasswd($old)
			->update(array('passwd'=>$new));
		if($is === 0) return -1;#老密码不正确
		if($is === 1) return true;#修改正确
		return false;#异常
    }

    /*
    #重置用户密码
    */
    public function resetPasswd($passwd, $id)
    {
		$passwd = $this->createPasswd($passwd);
		return $this->setId($id)->update(array('passwd'=>$passwd));
    }
    
	/*
	 * 对各字段的过滤， 用于过滤客户端提交来的数据
	 * 只对字段类型做处理，对长度不做处理，请在控制器做长度的处理
	 */
	public function filterItem($item)
	{
		if(empty($item)) return array();
		
		if(isset($item['id'])) $item['id'] = abs(intval($item['id']));
		if(isset($item['group_id'])) $item['group_id'] = abs(intval($item['group_id']));
		if(isset($item['name'])) $item['name'] = trim($item['name']);
		if(isset($item['truename'])) $item['truename'] = filterHtml(trim($item['truename']));
		if(isset($item['passwd'])) $item['passwd'] = trim($item['passwd']);
		if(isset($item['email'])) $item['email'] = filterHtml(trim($item['email']));
		if(isset($item['logins'])) $item['logins'] = abs(intval($item['logins']));
		if(isset($item['createtime'])) $item['createtime'] = abs(intval($item['createtime']));
		if(isset($item['edittime'])) $item['edittime'] = abs(intval($item['edittime']));
		if(isset($item['lasttime'])) $item['lasttime'] = abs(intval($item['lasttime']));
		if(isset($item['addip'])) $item['addip'] = filterHtml(trim($item['addip']));
		if(isset($item['lastip'])) $item['lastip'] = filterHtml(trim($item['lastip']));
		
		return $item;
	}


    #################################################


	/*
	#设置用户ID
	*/
	public function setId($d, $c = 'is')
	{
		$this->setWhere($this->tbl . '.id', $d, $c);
        return $this;
	}

	/*
	#设置用户名称
	*/
	public function setName($d, $c = 'is')
	{
		$this->setWhere($this->tbl . '.name', $d, $c);
        return $this;
	}


    /*
	#设置用户所属组ID
	*/
	public function setGroupId($d, $c = 'is')
	{
		$this->setWhere('group_id', $d, $c);
        return $this;
	}

    /*
	#设置用户组ID，连表时
	*/
	public function setGid($d, $c = 'is')
	{
		$this->setWhere($this->joinTableGroups . '.id', $d, $c);
        return $this;
	}

	/*
	#设置用户密码
	*/
	public function setPasswd($d, $c = 'is')
	{
		$this->setWhere('passwd', $d, $c);
        return $this;
	}

    /*
	#设置用户EMAIL
	*/
	public function setEmail($d, $c = 'is')
	{
		$this->setWhere('email', $d, $c);
        return $this;
	}

	/*
    #设置用户登陆次数
    */
    public function setLogins($d, $c='is')
    {
        return $this->setWhere('logins', $d, $c);
        return $this;
    }

    /*
	#设置用户账号开通时的IP
	*/
	public function setAddIp($d, $c = 'is')
	{
		$this->setWhere('addip', $d, $c);
        return $this;
	}

    /*
	#设置用户上次登录的IP
	*/
	public function setLastIp($d, $c = 'is')
	{
		$this->setWhere('lastip', $d, $c);
        return $this;
	}

	/*
	#设置用户账号开通时间的区间
	*/
	public function setAddTime($f, $t=0)
	{
		if(!empty($f) && !empty($t) && $f == $t){
			return $this->setWhere('addtime', $f);
		}else{
			if(!empty($f)){
	            $this->setWhere('addtime', $f, 'lmax');
	        }
	        if(!empty($t)){
	            $this->setWhere('addtime', $t, 'lmin');
	        }
		}
		return $this;
	}

    /*
	#设置用户上次登录时间的区间
	*/
	public function setLastTime($f, $t=0)
	{
		if(!empty($f) && !empty($t) && $f == $t){
			return $this->setWhere('lasttime', $f);
		}else{
			if(!empty($f)){
	            $this->setWhere('lasttime', $f, 'lmax');
	        }
	        if(!empty($t)){
	            $this->setWhere('lasttime', $t, 'lmin');
	        }
		}
		return $this;
	}

    /*
	#设置用户信息修改时间的区间
	*/
	public function setEditTime($f, $t=0)
	{
		if(!empty($f) && !empty($t) && $f == $t){
			return $this->setWhere('edittime', $f);
		}else{
			if(!empty($f)){
	            $this->setWhere('edittime', $f, 'lmax');
	        }
	        if(!empty($t)){
	            $this->setWhere('edittime', $t, 'lmin');
	        }
		}
		return $this;
	}

	/*
	#生产用户密码
	*/
	public function createPasswd($d)
	{
		return md5(md5(strrev($d)).$d);
	}




}



